package cn.bocai.pc.web.portal;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bocai.pc.model.BcDrawCollect;
import cn.bocai.pc.model.BcDrawing;
import cn.bocai.pc.model.BcUser;
import cn.bocai.pc.service.BcCollectService;
import cn.bocai.pc.service.BcDrawCollectService;
import cn.bocai.pc.service.BcDrawingService;
import cn.bocai.pc.service.BcLinktbleService;
import cn.bocai.pc.service.BcLinktypeService;
import cn.bocai.pc.service.BcPictureService;
import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;
import cn.bocai.pc.util.UUIDUtils;

/**
 * 改方法为分页方法
 * 
 * @time 2015/07/04
 */
@Controller
@RequestMapping("/bcDraw")
public class BaDrawingController {
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private BcLinktbleService bcLinktbleService;
	@Autowired
	private BcLinktypeService bcLinktypeService;
	@Autowired
	private BcCollectService bcCollectService;
	@Autowired
	private BcPictureService bcPictureService;
	@Autowired
	private VariableService variableService;
	@Autowired
	private BcDrawingService bcDrawingService;
	@Autowired
	private BcDrawCollectService bcDrawCollectService;
	

	/**
	 * 主页面进入全年图纸
	 * @throws ParseException 
	 * @time 2015/07/08
	 */
	@RequestMapping("/drawTrunK.do")
	public String drawTrunK(HttpServletRequest request, Model m) {
		// 到数据字典去查询出对的的值
		String variableYear = variableService.selectVariable("year");
		String draUrl = variableService.selectVariable("DRA_UEL");// /drawPic
		String baUrl = variableService.selectVariable("BA_URL");// http://localhost:8081
		m.addAttribute("year", variableYear);
		m.addAttribute("draUrl", draUrl);
		m.addAttribute("baUrl", baUrl);
		
		List<BcDrawing> returnColOrBlack = bcDrawingService.selectAllDraw(variableYear);
		m.addAttribute("drawGather", returnColOrBlack);
		
		return "bcPage/drawPic/drawPage";
	}
	
	 /**
 	 *全年图纸 收藏页面的ajax请求，保存收藏的数据
 	 * @throws ParseException 
 	 * @time 2015/07/07
 	 */
 	@RequestMapping("/sonInstallThumId.do")
 	public void sonInstallThumId(HttpServletRequest request, HttpServletResponse response,BcDrawCollect record,Model m){
 		BcUser attribute = (BcUser)request.getSession().getAttribute("selectLogin");
 		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
 		
 		if(null!=attribute){
			String uuid = request.getParameter("uuid");
			String year = request.getParameter("year");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id",attribute.getUserId());
			map.put("picId",uuid);
			map.put("year",year);
			//先去查询数据库是否有收藏改值
			BcDrawCollect queryEstimate = bcDrawCollectService.queryEstimate(map);
			//如果数据库有改值那么就是已收藏。
			if(null==queryEstimate){
				//judges传过来的值是add就是添加，如果传过来的是del就删除	
		    	Date date=new Date(); 
		    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		    	String format = dateFormat.format(date);
		    	record.setId(UUIDUtils.getUUID32());
		 		record.setBcUserId(attribute.getUserId());
		 		record.setColYear(year);
		 		record.setColTime(format);
		 		record.setPicId(uuid);
		 		int insert = bcDrawCollectService.insert(record);
		 		if(1 ==insert){
		 		 out.print("success");//收藏成功
		 		}else{
		 		 out.print("defeated");//收藏失败
		 		}
			}else{
				 out.print("already");//已收藏
			}
		}else{
			out.print("no");//表示未登入
		}
 	}
 	
 	// 登入成功进如收藏页面的3个页面
 		@RequestMapping("/afterLogin/afLoCollect.do")
 		public String publicAfterLogin(HttpServletRequest request,Model m) {
 		// 到数据字典去查询出对的的值
 			String variableYear = variableService.selectVariable("year");
 			String draUrl = variableService.selectVariable("DRA_UEL");// /drawPic
 			String baUrl = variableService.selectVariable("BA_URL");// http://localhost:8081
 			m.addAttribute("year", variableYear);
 			m.addAttribute("draUrl", draUrl);
 			m.addAttribute("baUrl", baUrl);
 			
 			CommPaging(request,m,variableYear);
 			return "bcPage/afterLogin/afLoDrawCollect";
 		}
 		
 		/**
 		 * 收藏页面首页的分页显示
 		 * @time 2015/09/07
 		 */
 		public void CommPaging(HttpServletRequest request,Model m,String year){
 			BcUser attribute =(BcUser)request.getSession().getAttribute("selectLogin");
 			        
 			      String _ps = request.getParameter("pageSize");
 			        //1:定义每页显示多少行记录
 					int pageSize = 12;
 					 //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
 					if(_ps!=null && !_ps.trim().equals("")){
 						try{
 							pageSize = Integer.parseInt(_ps);
 						}catch(Exception e){
 							//不处理
 						}
 					}
 					
 					//2:获取用户要求显示第几页
 					String _cp = request.getParameter("currentPageNumber");
 					//默认等于第一页
 					int currentPage = 1;
 			         //将获取到前台的用户要求的显示的第几页数据转化为整型类型数据
 					if(_cp!=null && !_cp.trim().equals("")){
 						try{
 							currentPage = Integer.parseInt(_cp);
 						}catch(Exception e){
 							//不处理
 						}
 					}
 					try{
 						//执行查询出全部数据的总行数
 						int rowCount = bcDrawCollectService.selectAllRow(attribute.getUserId());
 						//4:计算一共分多少页
 						int pageCount = rowCount/pageSize+(rowCount%pageSize==0?0:1);
 						//判断当前页面要求页数是否已经大于pageCount（总页数）最大页数，如果大于就拿总页数否则就拿页面要求的
 						currentPage=(currentPage>pageCount?pageCount:currentPage);
 						//判断
 				     	currentPage=(currentPage<=0?1:currentPage);
 						//5:计算从哪一行开始查询
 						int start = (currentPage-1)*pageSize;
 						
 						//6:查询出指定行数的数据
 						 Map<String, Object> map = new HashMap<String, Object>();
 						 map.put("userId",attribute.getUserId());
 						 map.put("year",year);
 						 map.put("start",start);
 						 map.put("pageSize",pageSize);
 						List<Map<String, Object>> moveList = bcDrawCollectService.getSelectCollect(map);
 						 
 						 
 						//封装数据将传到前台数据
 						 m.addAttribute("datas", moveList);//查询出的数据
 						 m.addAttribute("pageCount",pageCount);//一个分多少页
 						 m.addAttribute("currentPage", currentPage);//当前页数
 						 m.addAttribute("rowCount", rowCount);//一共多少条数据
 						 m.addAttribute("pageSize", pageSize);//每页显示的条数
 						 
 						//以下计算开始显示的页码和结束显示的页码
 							int showCount = 10;  //页面显示多少个页码
 							int showStart = 0;   //
 							int showEnd = 0;     //
 							//如果总页码还不够15页
 							if(pageCount<=showCount){
 								showStart=1;
 								showEnd=pageCount;//那么结束页面就等于总页码
 							}else{//分页显示页码
 								if(currentPage<=(showCount/2)){
 									showStart=1;
 									showEnd=showCount;
 								}else{
 									showStart=currentPage-(showCount/2-1);
 									showEnd=showStart+(showCount-1);
 								}
 								//如果showEnd已经超出总页面
 								if(showEnd>=pageCount){ //最后的页面大于等于总页码
 									showEnd=pageCount;
 									showStart=showEnd-(showCount-1);
 								}
 							}
 							m.addAttribute("showStart",showStart);
 							m.addAttribute("showEnd",showEnd);

 					}catch(Exception e){
 						throw new RuntimeException(e);
 					}
 		}
 		
 		/**
 		 * 全年图纸收藏页面图片删除
 		 * @throws ParseException 
 		 * @time 2015/07/07
 		 */
 		@RequestMapping("/afterLogin/delectThumOne.do")
 		public String delectThumOne(HttpServletRequest request,Model m) {
 			BcUser attribute = (BcUser)request.getSession().getAttribute("selectLogin");
 			String thumId = request.getParameter("uuid");
 			
 			 HashMap<String, String> map = new HashMap<String, String>();
 			 map.put("bcUserId", attribute.getUserId());
 			 map.put("id", thumId);
 			int delinsert = bcDrawCollectService.deleteBcCollect(map);
 			
 			if(1==delinsert){
 				m.addAttribute("msg", "删除成功");
 			}else{
 				m.addAttribute("msg", "删除失败");
 			}
 			m.addAttribute("skipUrl", "/bcDraw/afterLogin/afLoCollect.do");
 			return "bcPage/prompt/publicPrompt";
 		}
}
